package com.dm.library.http;

import com.dm.library.utils.DMLog;
import com.dm.library.utils.StringUtils;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: sushuo
 * 修改时间: 2017-05-16
 */
public class HttpParams extends BaseHttpParams {

    @Override
    public String toString() {
        String data = jsonObject.toString();
        DMLog.d(TAG, data);
        return data;
    }

    @Override
    public String makeGetUrl(String url) throws UnsupportedEncodingException {
        Iterator<String> keys = jsonObject.keys();
        url += "?";
        while (keys.hasNext()) {
            try {
                String key = keys.next();
                String value = jsonObject.getString(key);
                value = URLEncoder.encode(value, "utf-8");
                if (!StringUtils.isEmptyOrNull(value)) {
                    url += key + "=" + value + "&";
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (url.endsWith("?")) {
            url = url.substring(0, url.length() - 1);
        }
        if (url.endsWith("&")) {
            url = url.substring(0, url.length() - 1);
        }
        return url;
    }

    public Map<String, String> toMapParams() {
        Map<String, String> map = new HashMap<>();
        Iterator<String> keys = jsonObject.keys();
        while (keys.hasNext()) {
            try {
                String key = keys.next();
                String value = jsonObject.getString(key);
                map.put(key, value);
                DMLog.i(TAG, key + "=" + value);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

}